package com.mobi.Survey.lib.activities;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.mobi.Survey.lib.R;
import com.mobi.Survey.lib.db.AlarmTable;
import com.mobi.Survey.lib.model.AlarmPojo;
import com.mobi.Survey.lib.model.WebServiceIO;
import com.mobi.Survey.lib.utils.Helper;

public class AlarmScreen extends AbstractScreen {

	private AlarmPojo attr;
	private TextView tvTimerDescription;
	private ImageView ivTimerImage;

	private View btnOk;
	private View btnRemove;
	private View containerSnooze;
	private View btnfiveMinute;
	private View btnOneHour;
	private View btnOneDay;
	private View btnDelete;

	private Boolean timerListScreen = Boolean.FALSE;

	// trigger time is between upper and lower limit with respect to time
	private Boolean isTimeBetweenLimit = Boolean.FALSE;

	// current time is between upper and lower limit with respect to StartTime
	// private Boolean isStartTimeTimeBounds = Boolean.FALSE;

	private String okCancelDelete = "OK-Cancel-Delete";
	private String okCancel = "OK-Cancel";
	private String ok = "OK";
	private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

	@Override
	protected void onCreate(Bundle bundle) {

		super.onCreate(bundle);
		getExtras();

		showTimerImage();

		removeNotification();
		tvTimerDescription.setText(attr.getMessage());

		if (timerListScreen) {
			isTimeBetweenLimit = isStartTimeBetweenUpperAndLower();
			buttonsVisibilityForTimerListScreen();

		} else {
			setVisibilityByButtonAttribute();
		}

	}

	private Boolean isStartTimeBetweenUpperAndLower() {

		boolean isTimeBetweenLimit = false;

		try {
			if (null == attr.getUpperLimit() || null == attr.getLowerLimit()) {
				isTimeBetweenLimit = true;
				return isTimeBetweenLimit;

			}
			long upperLimit = Helper.stringTimeToMillis(attr.getUpperLimit());
			long lowerLimit = Helper.stringTimeToMillis(attr.getLowerLimit());

			if (lowerLimit == 0 && upperLimit == 0) {
				isTimeBetweenLimit = true;
				return isTimeBetweenLimit;
			}

			String lower = attr.getLowerLimit();
			String upper = attr.getUpperLimit();
			String start = attr.getStartTimeStr();

			Calendar cdCurrent = Calendar.getInstance();

			Calendar cdLower = Calendar.getInstance();
			Calendar cdUpper = Calendar.getInstance();
			Calendar temp = Calendar.getInstance();

			System.out.println("Current Time: " + cdCurrent.getTime());

			Calendar cdStart = Calendar.getInstance();
			long wrt = attr.calculateWrtInstallTime();
			if (wrt > 0) {
				cdStart.setTimeInMillis(wrt);
				temp.setTimeInMillis(wrt);
			} else {
				cdStart.setTime(sdf.parse(start));
			}

			temp.set(Calendar.HOUR_OF_DAY, cdStart.get(Calendar.HOUR_OF_DAY));
			temp.set(Calendar.MINUTE, cdStart.get(Calendar.MINUTE));
			temp.set(Calendar.SECOND, cdStart.get(Calendar.SECOND));
			cdStart.setTimeInMillis(temp.getTimeInMillis());

			cdUpper.setTime(sdf.parse(upper));
			temp.set(Calendar.HOUR_OF_DAY, cdUpper.get(Calendar.HOUR_OF_DAY));
			temp.set(Calendar.MINUTE, cdUpper.get(Calendar.MINUTE));
			temp.set(Calendar.SECOND, cdUpper.get(Calendar.SECOND));
			cdUpper.setTimeInMillis(temp.getTimeInMillis());

			cdLower.setTime(sdf.parse(lower));
			temp.set(Calendar.HOUR_OF_DAY, cdLower.get(Calendar.HOUR_OF_DAY));
			temp.set(Calendar.MINUTE, cdLower.get(Calendar.MINUTE));
			temp.set(Calendar.SECOND, cdLower.get(Calendar.SECOND));
			cdLower.setTimeInMillis(temp.getTimeInMillis());

			temp.setTimeInMillis(cdStart.getTimeInMillis());
			temp.add(Calendar.HOUR_OF_DAY, -cdLower.get(Calendar.HOUR_OF_DAY));
			temp.add(Calendar.MINUTE, -cdLower.get(Calendar.MINUTE));
			temp.add(Calendar.SECOND, -cdLower.get(Calendar.SECOND));
			cdLower.setTimeInMillis(temp.getTimeInMillis());

			temp.setTimeInMillis(cdStart.getTimeInMillis());
			temp.add(Calendar.HOUR_OF_DAY, cdUpper.get(Calendar.HOUR_OF_DAY));
			temp.add(Calendar.MINUTE, cdUpper.get(Calendar.MINUTE));
			temp.add(Calendar.SECOND, cdUpper.get(Calendar.SECOND));
			cdUpper.setTimeInMillis(temp.getTimeInMillis());

			if (upperLimit == 0) {
				if (cdCurrent.getTimeInMillis() >= cdLower.getTimeInMillis()) {
					isTimeBetweenLimit = true;

				}
			} else if (lowerLimit == 0) {
				if (cdCurrent.getTimeInMillis() <= cdUpper.getTimeInMillis()) {
					isTimeBetweenLimit = true;

				}
			} else if (cdCurrent.getTimeInMillis() <= cdUpper.getTimeInMillis()
					&& cdCurrent.getTimeInMillis() >= cdLower.getTimeInMillis()) {
				isTimeBetweenLimit = true;

			}

		} catch (ParseException e) {

			e.printStackTrace();
		} catch (Exception e) {

		}
		return isTimeBetweenLimit;

	}

	private void getExtras() {
		Intent intent = getIntent();
		if (intent == null || intent.getExtras() == null) {
			Log.e("Alarm Screen", "Bundle is null");

			finish();
			return;
		}

		attr = intent.getExtras().getParcelable("attributes");
		timerListScreen = intent.getExtras().getBoolean("timerListScreen");
	}

	private void showTimerImage() {
		try {
			String url = attr.getImageUrl();
			if (url != null) {

				String file = Helper.getPathToAppFolder()
						+ Helper.getHashNameFromUrl(url);

				ivTimerImage.setImageBitmap(BitmapFactory.decodeFile(file));
			}

		} catch (Exception e) {

		}
	}

	private void setVisibilityByButtonAttribute() {

		if (ok.equals(attr.getButtons())) {

			btnRemove.setVisibility(View.GONE);
			containerSnooze.setVisibility(View.GONE);
		}
		if (okCancelDelete.equals(attr.getButtons())) {
			btnfiveMinute.setVisibility(View.GONE);
			btnOneHour.setVisibility(View.GONE);
			btnOneDay.setVisibility(View.GONE);
		}
		if (okCancel.equals(attr.getButtons())) {

			containerSnooze.setVisibility(View.GONE);
		}

	}

	private void buttonsVisibilityForTimerListScreen() {

		if (isTimeBetweenLimit /* || isStartTimeTimeBounds */) {

			setVisibilityByButtonAttribute();
		} else {
			btnRemove.setVisibility(View.GONE);
			containerSnooze.setVisibility(View.GONE);
		}
	}

	private void removeNotification() {
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager nMgr = (NotificationManager) getSystemService(ns);
		nMgr.cancel(attr.getPendingIntentId());
	}

	@Override
	protected void initUiVars() {

		ivTimerImage = (ImageView) findViewById(R.id.ivTimerImage);
		tvTimerDescription = (TextView) findViewById(R.id.tvTimerDescription);

		// btnOk = findViewById(R.id.btnOk);
		btnRemove = findViewById(R.id.btnRemove);
		containerSnooze = findViewById(R.id.containerSnooze);
		btnfiveMinute = findViewById(R.id.btnfiveMinute);
		btnOneHour = findViewById(R.id.btnOneHour);
		btnOneDay = findViewById(R.id.btnOneDay);
		btnDelete = findViewById(R.id.btnDelete);

	}

	@Override
	protected int getLayoutId() {

		return R.layout.timer_start;
	}

	@Override
	protected void onRelease() {

	}

	private void snoozeAlarmFor(long milliSeconds, String text) {

		long snoozeTime = System.currentTimeMillis() + milliSeconds;
		Log.i("Snooze Time", new Date(snoozeTime).toLocaleString());
		attr.setRepeat(false);
		attr.setTriggerTime(snoozeTime);
		attr.setPendingIntentId((int) (System.currentTimeMillis() / 1000));
		Helper.setAlarm(this, attr);

		Toast.makeText(getApplicationContext(), "Alarm is snoozed for " + text,
				Toast.LENGTH_LONG).show();
		finish();
	}

	public void onClick(View v) {
		final int MINUTE = 1000 * 60;
		int id = v.getId();

		if (id == R.id.btnfiveMinute) {

			snoozeAlarmFor(MINUTE * 5, "5 minutes.");

		} else if (id == R.id.btnOneHour) {

			snoozeAlarmFor(MINUTE * 60, "1 hour.");
		} else if (id == R.id.btnOneDay) {

			snoozeAlarmFor(MINUTE * 60 * 24, "1 day.");

		} else if (id == R.id.btnRemove) {
			new AlarmOkCancelTask((byte) 0).execute();
		} else if (id == R.id.btnOk) {

			// if coming from Timer list screen
			if (timerListScreen) {
				if (!isTimeBetweenLimit) {
					finish();
				} else {
					new AlarmOkCancelTask((byte) 1).execute();
				}
			} else {

				// if coming due to timer trigger time should be in upper and
				// lower limit

				// if (!isStartTimeTimeBounds) {
				// finish();
				// } else {
				new AlarmOkCancelTask((byte) 1).execute();
				// }

			}

		} else if (id == R.id.btnDelete) {

			showDeleteConfirmation();

		}

	}

	private void showDeleteConfirmation() {

		final AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle(Messages.ARE_YOU_SURE);
		alert.setMessage(Messages.ALARM_WILL_BE_DELETE);

		alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				AlarmTable table = new AlarmTable(AlarmScreen.this);

				table.deleteRow(attr.getId());
				table.closeDB();

				PendingIntent pendingIntent = PendingIntent.getBroadcast(
						AlarmScreen.this, attr.getPendingIntentId(),
						new Intent(), 0);

				AlarmManager alarmManager = (AlarmManager) AlarmScreen.this
						.getSystemService(Context.ALARM_SERVICE);
				alarmManager.cancel(pendingIntent);

				Toast.makeText(getApplicationContext(),
						"Alarm Deleted Successfully.", Toast.LENGTH_LONG)
						.show();
				finish();
			}
		});

		alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

			}
		});
		alert.show();

	}

	private class AlarmOkCancelTask extends
			AsyncTask<Integer, Integer, Integer> {
		private byte isOk;

		AlarmOkCancelTask(byte isOk) {
			this.isOk = isOk;
		}

		ProgressDialog progressDialog = null;

		@Override
		protected void onPreExecute() {

			super.onPreExecute();

			progressDialog = ProgressDialog.show(AlarmScreen.this, "",
					Messages.SENDING);

		}

		@Override
		protected void onPostExecute(Integer result) {

			super.onPostExecute(result);

			progressDialog.dismiss();
			String message = null;
			if (result == 1) {
				message = "Data Sent.";
				Toast.makeText(getApplicationContext(), message,
						Toast.LENGTH_LONG).show();

				Intent intent = new Intent(AlarmScreen.this,
						SurveyListScreen.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

				finish();
			} else {
				message = "Data Send Failure.";
				Toast.makeText(getApplicationContext(), message,
						Toast.LENGTH_LONG).show();
			}

		}

		@Override
		protected Integer doInBackground(Integer... input) {
			String userId = getUserIdFromPreferences(AlarmScreen.this);
			boolean status = WebServiceIO.submitTimerStatus(getResources()
					.getString(R.string.timer_url), userId, isOk, attr);

			return status ? 1 : 0;
		}
	}

}
